import React, { useState, useEffect, useCallback } from 'react'

import { message, Table, Image, Button, Space, Tag, Row, Col, Popconfirm } from 'antd'
import { DeleteOutlined, FormOutlined, PlusOutlined, FileImageOutlined, ToTopOutlined } from '@ant-design/icons'
import { useNavigate, useSearchParams } from 'react-router-dom'
import axios from 'axios'
import request, { baseUrl } from '@/utils/request'
import { useStore, useSelector } from 'react-redux'

const List = () => {
    const [urlParams, setUrlParams] = useSearchParams()
    const [params, setParams] = useState({
        // 解决数据类型为string引起的bug
        page: Number(urlParams.get('page')) || 1,
        size: Number(urlParams.get('size')) || 10
    })
    const [total, setTotal] = useState(0)
    const navigate = useNavigate();


    const [datalist, setDatalist] = useState([]);
    let controller
    const getData = async () => {
        controller = new AbortController()
        const { data } = await request.get('/menu/selAlldishes', {
            params,
            signal: controller.signal
        })

        setDatalist(data.data)
        setTotal(data.total)
    }

    const userInfo = useSelector((state) => state.userInfo)

    // 商品操作CRUD
    const removeItem = useCallback(async (id) => {
        const { data } = await request.post('/menu/delDishes', { dishes_id: id })
        if (data.code === 200) {
            message.success('菜品删除成功')
            // 刷新页面方案一：重新请求数据
            getData()

            // 刷新页面方案二：修改state达到刷新的效果
            // setDatalist(datalist.filter(item=>item._id != id))
        }
    }, [datalist])
    const [selectIds, setSelectIds] = useState([])
    const removeItems = useCallback(async () => {
        if (selectIds.length === 0) {
            return message.warning('请选择删除的菜品');
        }
        const { data } = await request.post('/menu/delSome', {
            // headers: {
            //     Authorization: userInfo.authorization
            // },

            ids: selectIds

        })

        if (data.code === 200) {
            message.success('菜品删除成功')
            getData()
        }
    }, [selectIds])
    const addItem = useCallback(() => {
        navigate('/manage/goods/add')
    }, [])
    const editItem = useCallback((id) => navigate('/manage/goods/' + id), [])

    const columns = [
        {
            title: '#',
            key: '_id',
            width: 10,
            render(text, record, index) {
                return index + 1
            }
        },
        {
            title: '菜品图片',
            dataIndex: 'dishes_img',
            width: 120,
            //自定义单元格内容
            render: (text, record, index) => {
                // text: 当前列数据(dataIndex对应的数据，如无dataIndex,text与record一致)
                // record: 当前行数据
                // index: 当前索引值
                // console.log(text, record, index)
                return <Image src={text} />
            }
        },
        {
            title: '菜品信息',
            dataIndex: 'dishes_name',
            width: 300,
            render(text, item) {
                return (
                    <>
                        <h4>{text}</h4>
                        <Tag color='success'>{item.category}</Tag>
                        <p className='price'>
                            {
                                item.sales_price ?
                                    <><del>￥{item.price}</del><span>￥{item.sales_price}</span></>
                                    :
                                    <span>￥{item.price}</span>
                            }
                        </p>
                    </>
                )
            }
        },
        {
            title: '上/下架',
            dataIndex: 'online',
            render(text, item) {
                return (
                    <>
                        <h4>{text==1?"上架":"下架"}</h4>
                    </>
                )
            }
        },
        {
            title: '菜品库存',
            dataIndex: 'dishes_qty',
            render(text, item) {
                return (
                    <>
                        <h4>{text}</h4>
                    </>
                )
            }
        },
        {
            title: '操作',
            dataIndex: 'dishes_id',
            width: 100,
            render(id) {
                return (
                    // <React.Fragment>
                    <Space>
                        <Button ghost type='primary' icon={<FormOutlined />} size="small" onClick={editItem.bind(null, id)}></Button>
                        <Popconfirm
                            title="确认删除"
                            onConfirm={removeItem.bind(null, id)}
                        >
                            <Button danger icon={<DeleteOutlined />} size="small"></Button>

                        </Popconfirm>
                    </Space>
                )
            }
        },
    ]
    const rowSelection = {
        onChange(selectedRowKeys) {
            console.log('selectedRowKeys=', selectedRowKeys)
            setSelectIds(selectedRowKeys)
        }
    }
    const pagination = {
        total,
        current: params.page,
        pageSize: params.size,
        size: 'small',
        onChange(page, size) {
            setParams({
                page,
                size
            })

            setUrlParams({
                page,
                size
            })
        }
    }


    useEffect(() => {
        getData();

        return function () {
            // 取消ajax
            controller.abort()
        }
    }, [params])



    return (
        <div>
            <Row gutter={20}>
                <Col span={8}>
                    <Button type='primary' icon={<PlusOutlined />} onClick={addItem}>添加</Button>
                </Col>
                <Col span={16} className='text-right'>
                    <Space>
                        <Button type='primary' ghost icon={<ToTopOutlined />}>上下架</Button>
                        <Popconfirm
                            title="确认删除"
                            onConfirm={removeItems}
                        >
                            <Button danger icon={<DeleteOutlined />}>批量删除</Button>

                        </Popconfirm>

                    </Space>
                </Col>
            </Row>
            <Table
                style={{ marginTop: 20 }}
                rowKey="dishes_id"
                rowSelection={rowSelection}
                columns={columns}
                dataSource={datalist}
                pagination={pagination}
            />
        </div>

    )
}

export default List;